package hidalgo.expenses.dao;

import hidalgo.expenses.utils.Properties;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.util.Log;

public class MyHttpClient {

	static String URL = "";
	static final String TAG = "HttpClient";

	ArrayList<NameValuePair> nameValuePairs;

	public MyHttpClient(String URL_) {
		URL = URL_;
		nameValuePairs = new ArrayList<NameValuePair>();
		
		addDataToSend("usernamephp", Properties.DBuserName);
		addDataToSend("passwordphp", Properties.DBpassword);
		addDataToSend("databasephp", Properties.DB);
		addDataToSend("hostphp", Properties.DBhost);
	}

	public void addDataToSend(String dataName, String value) {
		nameValuePairs.add(new BasicNameValuePair(dataName, value));
	}

	public JSONObject executeHttpPost() {
		StringBuilder sb = null;
		String result = null;

		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpPost httpPostRequest = new HttpPost(URL);

			// put data to send
			httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			HttpResponse response = (HttpResponse) httpclient
					.execute(httpPostRequest);

			// get hold of the response entity (-> the data):
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				// read the content stream
				InputStream instream = entity.getContent();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(instream, "iso-8859-1"), 8);
				sb = new StringBuilder();

				// read line by line
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
					Log.d("MyhttpClient line by line", "" + line);
				}
				instream.close();

				result = sb.toString();

				// transform the String into a JSONObject
				JSONObject jsonObjRecv = new JSONObject(result);

				return jsonObjRecv;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
